package codeine.servlets;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import codeine.configuration.ConfigurationManager;
import codeine.configuration.Links;
import codeine.configuration.PathHelper;
import codeine.model.Constants;
import codeine.servlet.AbstractServlet;
import codeine.servlet.HtmlHeaderWriter;
import codeine.utils.FilesUtils;
import codeine.utils.HttpUtils;

import com.google.inject.Inject;

public class CommandLogServlet extends AbstractServlet {
	private static final Logger log = Logger.getLogger(CommandLogServlet.class);
	private static final long serialVersionUID = 1L;

	@Inject	private ConfigurationManager configurationManager;
	@Inject	private NodeAggregator aggregator;
	@Inject private HtmlHeaderWriter htmlHeaderWriter;
	@Inject private PathHelper pathHelper;
	@Inject private Links links;
	
	@Override
	protected void myGet(HttpServletRequest request, HttpServletResponse response) {
		log.debug("aggregate request");
		String projectName = request.getParameter("project");
		PrintWriter writer = getWriter(response);
		htmlHeaderWriter.writeHeader(request, response, projectName, projectName + " / aggregate");
		String dir = pathHelper.getPluginsOutputDir(projectName);
		List<String> filesInDir = FilesUtils.getFilesInDir(dir);
		for (String file : filesInDir) {
			String line = "            <alert><div class=\"alertbar\"><ul>";
			String className = "g";
			String versionClass = "version" + className;
			String versionLabel = file;
			String l = links.getPluginOutLink(projectName, file);
			String projectParams = "?project=" + HttpUtils.encode(projectName) + "&path=" + HttpUtils.encode("command log") + "&link=" + HttpUtils.encode(l);
			String link = Constants.RAW_OUTPUT_CONTEXT + projectParams;
			line += "<li><a class=\"" + versionClass + "\" href=\""+link+"\">" + versionLabel + "</a></li>";
			line += "</ul><br style=\"clear:left\"/></div></alert>";
			writer.println(line);
		}
		htmlHeaderWriter.writeFooter(response);
	}

}
